#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HeilongjiangHaerbinQu2Policy(BaseTaxPolicySpider):
    name = 'heilongjiang_haerbin_qu2_policy'
    
    province = '黑龙江省'
    city: str = "哈尔滨市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['尚志市人民政府', '尚志市', 'http://www.shangzhi.gov.cn/szsrmzf/c100381/xxgklist_zhengce.shtml'],
            ['尚志市人民政府', '尚志市', 'http://www.shangzhi.gov.cn/szsrmzf/c100382/xxgklist_zhengce.shtml'],
            ['尚志市人民政府', '尚志市', 'http://www.shangzhi.gov.cn/szsrmzf/c100384/xxgklist_zhengce.shtml'],
            ['尚志市人民政府', '尚志市', 'http://www.shangzhi.gov.cn/szsrmzf/c100383/xxgklist_zhengce.shtml'],
            ['巴彦县人民政府', '巴彦县', 'https://www.bayan.gov.cn/hebbyx/xszfwj/zc.shtml'],
            ['巴彦县人民政府', '巴彦县', 'https://www.bayan.gov.cn/hebbyx/zfbwj/zc.shtml'],
            ['巴彦县人民政府', '巴彦县', 'https://www.bayan.gov.cn/hebbyx/bmwj/zc.shtml'],
            ['巴彦县人民政府', '巴彦县', 'https://www.bayan.gov.cn/hebbyx/qtwj/zc.shtml'],
            ['宾县人民政府', '宾县', 'http://www.chinabx.gov.cn/hebbx/c109406/zc.shtml'],
            ['宾县人民政府', '宾县', 'http://www.chinabx.gov.cn/hebbx/c109407/zc.shtml'],
            ['宾县人民政府', '宾县', 'http://www.chinabx.gov.cn/hebbx/c109408/zc.shtml'],
            ['宾县人民政府', '宾县', 'http://www.chinabx.gov.cn/hebbx/c109409/zc.shtml'],
            ['依兰县人民政府', '依兰县', 'https://www.hrbyl.gov.cn/hebylx/qxszfwj/zfxxgklby.shtml'],
            ['依兰县人民政府', '依兰县', 'https://www.hrbyl.gov.cn/hebylx/qxszfbwj/zfxxgklby.shtml'],
            ['依兰县人民政府', '依兰县', 'https://www.hrbyl.gov.cn/hebylx/bmwj/zfxxgklby.shtml'],
            ['依兰县人民政府', '依兰县', 'https://www.hrbyl.gov.cn/hebylx/qtwj/zfxxgklby.shtml'],
            ['木兰县人民政府', '木兰县', 'http://www.mulan.gov.cn/hebmlx/qxszfwj/zfxxgklby.shtml'],
            ['木兰县人民政府', '木兰县', 'http://www.mulan.gov.cn/hebmlx/qxszfbwj/zfxxgklby.shtml'],
            ['木兰县人民政府', '木兰县', 'http://www.mulan.gov.cn/hebmlx/bmwj/zfxxgklby.shtml'],
            ['木兰县人民政府', '木兰县', 'http://www.mulan.gov.cn/hebmlx/qtwj1/zfxxgklby.shtml'],
            ['方正县人民政府', '方正县', 'http://www.hrbfz.gov.cn/fzx/qxszfwj/zfxxgklby.shtml'],
            ['方正县人民政府', '方正县', 'http://www.hrbfz.gov.cn/fzx/qxszfbwj/zfxxgklby.shtml'],
            ['方正县人民政府', '方正县', 'http://www.hrbfz.gov.cn/fzx/bmwj/zfxxgklby.shtml'],
            ['方正县人民政府', '方正县', 'http://www.hrbfz.gov.cn/fzx/qtwj/zfxxgklby.shtml'],
            ['通河县人民政府', '通河县', 'http://www.hrbtonghe.gov.cn/hebthxx/c109686/zc.shtml'],
            ['通河县人民政府', '通河县', 'http://www.hrbtonghe.gov.cn/hebthxx/c109687/zc.shtml'],
            ['通河县人民政府', '通河县', 'http://www.hrbtonghe.gov.cn/hebthxx/c109688/zc.shtml'],
            ['通河县人民政府', '通河县', 'http://www.hrbtonghe.gov.cn/hebthxx/c109689/zc.shtml'],

        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='table-main' or @class='table-responsive' or @class='govnewslista2353']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//div[@class='table-main' or @class='zfxxgk_right']//dd//a[contains(@href, 'htm') or @title]/ancestor::dd[string-length(string(.))>=2] |"
                "//table[@id='gk_list_table' or @class='table']/tr/td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//td[@class='info']//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=2] |"
                "//div[@class='list_right']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=2]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or response.xpath("//script").re_first(r"""createPageHTML\('paging',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl heilongjiang_haerbin_qu2_policy".split())
